package io.gitee.kotle.demo

import android.content.res.Configuration
import android.graphics.Color
import android.os.Bundle
import android.view.Gravity
import android.view.View
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import io.gitee.kotle.android.adapter.*
import io.gitee.kotle.android.drawable.CenterTextDrawable
import io.gitee.kotle.android.mvvm.binding.IMvvmBinding
import io.gitee.kotle.android.utils.*
import io.gitee.kotle.base.library.BaseBindingActivity
import io.gitee.kotle.demo.databinding.ActivityMainBinding
import io.gitee.kotle.demo.mvvm_demo.DemoBottomSheetDialog
import io.gitee.kotle.demo.mvvm_demo.DemoDialog
import io.gitee.kotle.demo.mvvm_demo.DemoPopup
import io.gitee.kotle.demo.mvvm_demo.hsp.HspFragment
import io.gitee.kotle.demo.mvvm_demo.lottie.LottieFragment
import io.gitee.kotle.demo.mvvm_demo.pic.BannerFragment
import io.gitee.kotle.demo.mvvm_demo.pic.FileDownloadFragment
import io.gitee.kotle.demo.mvvm_demo.pic.PicFragment
import io.gitee.kotle.demo.mvvm_demo.websocket.WebSocketFragment
import io.gitee.kotle.demo.skin_view.skin.BaseSkinPackage
import io.gitee.kotle.demo.skin_view.skin.SkinManage
import io.gitee.kotle.demo.skin_view.skin.skin_package.SkinPackage1
import kotlinx.coroutines.launch
import java.lang.NullPointerException
import java.util.*

open class BaseMain<Data> : BaseBindingActivity<ActivityMainBinding>() {
    override fun getViewBindingClass(self: IMvvmBinding<ActivityMainBinding>): Class<ActivityMainBinding> {
        return ActivityMainBinding::class.java
    }
}

class MainActivity : BaseMain<Date>() {

    private val cameraPermission = permissionForResult()

    private val adapter = recyclerViewAdapter<Pair<String, (View) -> Unit>>().apply {
//       方式1，通过ViewBinding创建
//        recyclerViewHolder(AppHolder::simpleText)
        //方式2，通过view绑定
//        recyclerViewHolder({ layoutInflater, viewGroup ->
//            HolderTextBinding.inflate(layoutInflater, viewGroup, false).root
//        }, AppHolder::simpleText1)
        //3
        register(TextHolder::class.java, 9988)
    }

    private val imeHelper by lazy {
        ImeHelper.invoke(this).also {
            it.setOnImeListener { imeOffset, imeMaxHeight, statusBarHeight, navigationBarHeight ->
                println("----------键盘高度：$imeOffset")
            }
        }
    }

    override fun initUi(savedInstanceState: Bundle?) {
        super.initUi(savedInstanceState)
        fullScreen(true)
        mBinding.rcv.adapter = adapter
        window.statusBarColor = Color.RED
        window.navigationBarColor = Color.GREEN
        adapter.refreshList(getDatas())
        mBinding.text.background = CenterTextDrawable().also {
            it.text = "东风快递放暑假快点放暑假地方"
        }
        mBinding.text.textFromSpanBean(
            SpanBean("1111\n"),
            SpanBean("22222", lineHeight = 100.dp, gravity = Gravity.TOP),
            SpanBean("\n1111"),
        )

    }

    private val activityResult = activityForResult()
    private fun getDatas(): MutableList<Pair<String, (View) -> Unit>>? {
        return mutableListOf(
            Pair("切换为英文") {
                updateLocal(Locale.ENGLISH.toLanguageTag())
                recreate()
            },
            Pair("切换为中文") {
                updateLocal(Locale.CHINA.toLanguageTag())
                recreate()
            },
            Pair("横竖屏测试") {
                HspFragment.start(appCompatActivity)
            },
            Pair("加载图片示例") {
                PicFragment.start(appCompatActivity, activityResult)
            },
            Pair("Alert") {
                //  showDialog<AlertDialog>()
            },
            Pair("Lottie") {
                LottieFragment.start(appCompatActivity)
            },
            Pair("请求权限示例") {
                //相机权限请求回调
                cameraPermission.launch(android.Manifest.permission.CAMERA) {
                    "${android.Manifest.permission.CAMERA}:${it}".toast()
                }
            },
            Pair("popupWindow") {
                DemoPopup().showAtView(it, false, isDropViewBottom = false)
            },
            Pair("SheetDialog") {
                showDialog<DemoBottomSheetDialog>()
            },
            Pair("Dialog") {
                println("-----${window.decorView.imeVisible()}")
                imeHelper.hideIme {
                    showDialog<DemoDialog> {
                        "对话框已销毁".toast()
                    }
                }
            },
            Pair("banner") {
                startFragment<BannerFragment>()
            },
            Pair("文件下载") {
                startFragment<FileDownloadFragment>()
            },
            Pair("让APP崩溃") {
                lifecycleScope.launch {
                    throw NullPointerException("测试崩溃")
                }
            },
            Pair("切换皮肤") {
                SkinManage.updateSkin(SkinPackage1())
            },
            Pair("恢复皮肤") {
                SkinManage.updateSkin(BaseSkinPackage())
            },
            Pair("打开应用市场") {
                goAppMarket("com.tencent.mm")
            },
            Pair("打开GooglePlay") {
                goGooglePlay("com.tencent.mm")
            },
            Pair("WebSocket") {
                WebSocketFragment.start(this)
            },
        )
    }

    override fun isNeedToolBar(): Boolean {
        lifecycleScope.launchWhenCreated {
            lifecycle.repeatOnLifecycle(Lifecycle.State.STARTED) {
                log { "Lifecycle.State.STARTED" }
                awaitAny<Int> {
                    it.invokeOnCancellation {
                        log { "协程已取消" }
                    }
//                    it.resume(1)
                }
            }
        }
        return true
    }

    override fun onDestroy() {
        super.onDestroy()
    }


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
    }

    override fun onStart() {
        super.onStart()
    }

    override fun onConfigurationChanged(newConfig: Configuration) {
        super.onConfigurationChanged(newConfig)
        log { "当前onConfigurationChanged发生变化" }
    }

    override fun onScreenOrientationPortrait() {
        super.onScreenOrientationPortrait()
        log { "当前是竖屏" }
    }

    override fun onScreenOrientationLandscape() {
        super.onScreenOrientationLandscape()
        log { "当前是横屏" }
    }

    override fun onScreenOrientationChange(isPortrait: Boolean) {
        super.onScreenOrientationChange(isPortrait)
        log { "当前屏幕发生变化：$isPortrait" }
    }
}